package progetto6.jade;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class Logger {
	
	private Choice[][] choices;
	private int columnFixer = 0;
	private List<Strategy> strategyRegistry = new LinkedList<Strategy>();
	private int cnt = 0;
	private final String file;

	public Logger(String file, int iteration, int numStrategy) {
		assert numStrategy % 2 == 0;
		choices = new Choice[iteration][numStrategy];
		this.file = file;
	}

	public void toLog(int iteration, int pid, Choice c) {
		choices[iteration][columnFixer + pid] = c;
		cnt++;
		if(iteration == choices.length-1 && cnt == 2)
			columnFixer+=2;
		if(cnt == 2){
			cnt = 0;
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < choices.length; i++) {
			for (int j = 0; j < choices[0].length; j++) {
				if(j == choices[0].length-1) 
					sb.append(choices[i][j]+"\n");
				else
					sb.append(choices[i][j]+ ",");
			}
		}
		return sb.toString();
	}

	public void save() {
		try {
			File f = new File(file);
			if (!f.exists()) {
				f.createNewFile();
			}
			CSVPrinter printer = new CSVPrinter(new FileWriter(f),
					CSVFormat.EXCEL.withDelimiter(';'));
			printer.print("Iterazione");
			for (Strategy strategy : strategyRegistry) {
				printer.print(strategy);
			}
			printer.println();
			for (int i = 0; i < choices.length; i++) {
				printer.print(new Integer(i+1));
				for (int j = 0; j < choices[0].length; j++) {
					printer.print(choices[i][j]);
				}
				printer.println();
			}
			printer.print("Score D:");
			for (Strategy strategy : strategyRegistry) {
				AbstractStrategy as = (AbstractStrategy) strategy;
				printer.print(new Integer(as.getScore(Choice.D)));
			}
			printer.println();
			printer.print("Score C:");
			for (Strategy strategy : strategyRegistry) {
				AbstractStrategy as = (AbstractStrategy) strategy;
				printer.print(new Integer(as.getScore(Choice.C)));
			}
			printer.println();
			printer.close();
		} catch (IOException e) {
			System.out.println("Impossibile salvare i risultati");
		}
	}

	public void registry(Strategy strategy) {
		strategyRegistry.add(strategy);
	}
	
}
